﻿using System;
using Atmk.WaterMeter.MIS.TestForm.Common;
using Atmk.WaterMeter.MIS.TestForm.Dialogs;
using Atmk.WaterMeter.MIS.TestForm.Views.DataMock.vo;
using Common.Logging;
using Newtonsoft.Json;
using NKnife.IoC;
using RestSharp;

namespace Atmk.WaterMeter.MIS.TestForm.Views.DataMock.Helper
{
    /// <summary>
    ///     创建片区
    /// </summary>
    internal class UtilBuildDistrict
    {
        private static readonly ILog _Logger = LogManager.GetLogger<UtilBuildDistrict>();
        private readonly CurrentMock _current;

        private readonly Kernel _kernel;

        public UtilBuildDistrict()
        {
            _kernel = DI.Get<Kernel>();
            _current = DI.Get<CurrentMock>();
        }

        public void Run(int count)
        {
            for (var i = 0; i < count; i++)
            {
                var request = new RestRequest(UrlManager.InsertDistricts, Method.POST);
                request.AddHeader("X-Token", _kernel.Token);

                var name = _current.GetDistrictName();
                var d = new district(_current.AreaId, string.Empty, name);
                request.AddJsonBody(d);
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var data = response.Content;
                    _Logger.Trace(data);
                    try
                    {
                        var districtReturn = JsonConvert.DeserializeObject<BaseAddResult>(data);
                        var districtId = districtReturn.id;
                        _current.SaveDistrict(districtId, name);
                    }
                    catch (Exception exception)
                    {
                        _Logger.Error(exception);
                    }

                    _Logger.Trace($"{d.ToString()}创建成功");
                });
            }
        }
    }

    public class BaseAddResult : Result
    {
        public string id { get; set; }
    }
}